<?php
namespace cms\modules\v1\models\shop;

use cms\modules\v1\models\Common;
use cms\modules\v1\models\express\ExpressCompany;
use cms\modules\v1\models\images\Images;
use cms\modules\v1\models\user\User;
use common\models\Functions;
use common\models\Status;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;
use yii\helpers\StringHelper;

/**
 * Class UserActiveRecord
 * @package cms\modules\v1\models
 */
class GoodsOrder extends \common\models\shop\GoodsOrder
{

    public function getHeader($searchWhere = []) {
        $start = date('Y-m-d');
        $end = date('Y-m-d');
        $dataStartAndEnd = Functions::getDay($start,$end);
        $andWhere[] = [];
        $data['total'] = static::getCountByAndWhere([],$andWhere);
        $andWhere = $where = [];
        $andWhere[] = ['between','create_time',$dataStartAndEnd['start'], $dataStartAndEnd['end']];
        $where['status'] = Status::USER_GOODS_ORDER_STATUS_WAITING_SEND;
        $data['today'] = static::getCountByAndWhere($searchWhere['where'],$andWhere);

        $dataStartAndEnd = Functions::getDay(date('Y-m-d',strtotime('+1 day')),date('Y-m-d',strtotime('+1 day')));
        $andWhere = $where = [];
        $where['status'] = Status::USER_GOODS_ORDER_STATUS_WAITING_SEND;
        $andWhere[] = ['between','create_time',$dataStartAndEnd['start'], $dataStartAndEnd['end']];
        $data['tomorrow'] = static::getCountByAndWhere($searchWhere['where'],$andWhere);

        $dataStartAndEnd = Functions::getDay(date( "Y-m-d H:i:s", mktime ( 0, 0, 0, date ( "m" ), 1, date ( "Y" ) ) ),date ( "Y-m-d H:i:s", mktime ( 23, 59, 59, date ( "m" ), date ( "t" ), date ( "Y" ) ) ));
        $andWhere = $where = [];
        $andWhere[] = ['between','create_time',$dataStartAndEnd['start'], $dataStartAndEnd['end']];
        $data['month'] = static::getCountByAndWhere($searchWhere['where'],$andWhere);
        return $data;
    }


    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getListData($page = 1, $size = 20) {
        try {

            //搜索条件
            $searchWhere  = $this->getSearch();//自定义搜索条件
            //得到文章的总数
            $count = static::getObjectCountByAndWhere($searchWhere['where'], $searchWhere['andWhere'])->count();
            $data = static::setPageinationAPI($page, $size, $count);
            //设置分页
            $offset = ($page - 1) * $size;

            //排序 order
            $orderSql = 'create_time DESC';

            $query = static::getObjectByAndWhere($searchWhere['where'],$searchWhere['andWhere'], '*', $orderSql, $offset, $size);
            $data['data'] = $this->handelList($query);

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     * @return string
     */
    public function getSearch () {
        $where = [];
        $andWhere = [];
        $where['is_delete'] = Status::COMMON_IS_NOT_DELETE;
        $status = Yii::$app->request->get('status','');
        $type = Yii::$app->request->get('type','');
        $orderNumber = Yii::$app->request->get('order_number','');
        $loginName = Yii::$app->request->get('login_name','');
        $startTime = Yii::$app->request->get('start','');
        $endTime = Yii::$app->request->get('end','');

        if ($status) {
            $where['status'] = (int) $status;
        }

        if ($type) {
            $type_id = \common\models\shop\Goods::searchByType($type);
            $where['goods_id'] = $type_id;
        }
        if ($orderNumber) {
            $andWhere[] = ['like','order_number',$orderNumber];
        }
        if ($loginName) {
            $ids = \common\models\user\User::searchByName($loginName);
            $where['sell_user'] = $ids;
        }

        if(!empty($startTime) && empty($endTime)) {
            $andWhere[] = ['>','create_time',$startTime];
        } elseif(empty($startTime) && !empty($endTime)) {
            $andWhere[] = ['<','create_time',$endTime];
        } elseif (!empty($startTime) && !empty($endTime)) {
            $andWhere[] = ['between','create_time',$startTime, $endTime];
        }

        return [
            'where' => $where,
            'andWhere' => $andWhere,
        ];
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handelList($query = null) {
        if (empty($query)) {
            return null;
        }
        $list = $query->with([
            'user', 'goods','address'
        ])->asArray()->all();

        foreach ($list as &$v) {
            $v['user']['user_face'] = static::getImages($v['user']['user_face']);
            $v['pay_way'] = Status::PAY_WAY_MAP[$v['pay_way']] ?? '';
        }
        return $list;
    }


    /**
     * 订单发货
     * @return array
     */
    public function deliver() {
        try {
            $expressId = Yii::$app->request->post('express_id',0);
            $expressNo = Yii::$app->request->post('express_no','');
            $orderId = Yii::$app->request->post('order_id',0);

            $orderInfo = static::getOneInfoById($orderId);

            if(empty($orderInfo)) {
                throw new Exception('未知订单信息');
            }

            if ($orderInfo['status'] != Status::USER_GOODS_ORDER_STATUS_WAITING_SEND) {
                throw new Exception('该订单未在待发货中');
            }

            $update['status'] = Status::USER_GOODS_ORDER_STATUS_WAITING_RECEIVE;
            $update['deliver_goods_time'] = date("Y-m-d H:i:s");
            $update['express_id'] = 0;
            $update['express_number'] = '';
            $update['express_name'] = '无快递';
            if ($expressId) {
                $expressMap = ExpressCompany::getListMapByCache();
                $expressInfo = $expressMap[$expressId];
                $update['express_id'] = $expressId;
                $update['express_name'] = $expressInfo['express_name'];
                $update['express_number'] = $expressNo;
            }

            $res = static::updateData($update, ['id' => $orderId]);

            if ($res === false) {
                throw new Exception('系统错误，请联系开发小哥哥');
            }
            return Functions::formatRestAPI(0, '发货成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 获取订单信息
     * @param int $id
     * @return array
     */
    public function getInfo($id = 0) {
        try {
            if (empty($id)) {
                throw new Exception('未知信息');
            }
            $where['id'] = $id;
            $orderInfo = static::getObjectOneByWhere($where)->with([
                'goods','user','sell'])->asArray()->one();
            if (empty($orderInfo)) {
                throw new Exception('未找到订单信息');
            }

            $data = [
                'id' => (int) $orderInfo['id'],
                'order_number' => $orderInfo['order_number'],
                'login_name' => $orderInfo['user']['login_name'],
                'nick_name' => $orderInfo['user']['nick_name'],
                'goods_content' => $orderInfo['goods']['content'],
                'num' => $orderInfo['num'],
                'real_money' => $orderInfo['real_money'],
                'freight' => $orderInfo['freight'] ?: '0',
                'money' => $orderInfo['money'] ?: '0',

                'sell_login_name' => $orderInfo['sell']['login_name'],
                'sell_nick_name' => $orderInfo['sell']['nick_name'],

                'express_number' => $orderInfo['express_number']?:'暂无',
                'express_name' => $orderInfo['express_name']?:'暂无',

                'link_user' => $orderInfo['link_user'],
                'link_phone' => $orderInfo['link_phone'],
                'address_detail' => $orderInfo['address_detail'],

                'create_time' => $orderInfo['create_time'],
                'pay_time' => $orderInfo['pay_time'] ?: '暂无',
                'cancel_time' => $orderInfo['cancel_time'] ?? '暂无',
                'deliver_goods_time' => $orderInfo['deliver_goods_time'] ?: '暂无',
                'finished_time' => $orderInfo['finished_time'] ?: '暂无',

                'status' => $orderInfo['status'],
                'statusName' => Status::USER_GOODS_ORDER_STATUS_MAP[$orderInfo['status']],
                'pay_way' => Status::PAY_WAY_MAP[$orderInfo['pay_way']],
                'goods_type' => $orderInfo['goods_type'],
                'goods_type_name' => Status::GOODS_TYPE_MAP[$orderInfo['goods_type']],
            ];
            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 编辑订单信息
     * @return array
     */
    public function saveInfo() {
        try {
            $post = Yii::$app->request->post();

            $id = (int) $post['id'];

            $data['receive_address'] = $post['address'];
            $data['receive_user'] = $post['user'];
            $data['receive_phone'] = $post['phone'];

            $res = static::updateData($data, ['id' => $id]);
            if ($res === false) {
                throw new Exception('系统错误');
            }

            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    public function getStatusMap() {
        $result = [];
        foreach (Status::USER_GOODS_ORDER_STATUS_MAP as $k => $v) {
            $result[] = [
                'id' => (int) $k,
                'name' => $v,
            ];
        }
        return Functions::formatRestAPI(0, '', $result);
    }

    //客户一周注册表
    public function weekOrder() {
        $date = time() - 24 * 3600 * 7;
        $data = [];
//        $cache = \Yii::$app->cache;
        for ($i = 1; $i <= 7; $i ++) {
            $currDate = strval(date("Y-m-d", $date + $i * 24 * 3600)) ;
//            $registerNum = $cache->get($currDate . "_register");
            $registerNum = [];
            if (empty($registerNum)) {
                $currDateStart = $currDate. ' 00:00:00';
                $currDateEnd = $currDate. ' 23:59:59';
                $andWhere = ['between','pay_time',$currDateStart, $currDateEnd];
                $registerNum  = (int) static::getSumByAndWhere([], $andWhere,'pay_money');
//                $cache->set($currDate . "_register", $registerNum);
            }
            $data[] = [$currDate,$registerNum];
        }
        return Functions::formatRestAPI(0, '', $data);
    }

    /**
     * 删除订单
     * @param $id
     * @return array|bool
     */
    public static function goodsOrderDelete($id = 0) {
        try {
            $id = !$id ? Yii::$app->request->post('id') : $id;

            if (empty($id)) {
                throw new Exception('信息错误');
            }

            if (!empty($id) && is_array($id)) {

                $info = static::getInfoById($id);
            } elseif(is_numeric($id) && intval($id)) {

                $info = static::getOneInfoById($id);
            }

            if (empty($info)) {
                throw new Exception('未知信息');
            }

            $data['is_delete'] = Status::COMMON_IS_DELETE;
            if (static::updateData($data, ['id' => $id]) === false) {
                throw new Exception('删除失败');
            }

            return Functions::formatRestAPI(0, '删除成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 取消订单
     * @param $id
     * @return array|bool
     */
    public function orderCancel() {
        $trans = \Yii::$app->db->beginTransaction();
        try {
            $id = Yii::$app->request->post('id','');
            $reason = Yii::$app->request->post('reason','');
            if (empty($id)|| empty($reason)){
                throw new Exception('缺少参数');
            }

            $orderInfo = static::getOneInfoById($id);
            if (empty($orderInfo)) {
                throw new Exception('未知订单信息');
            }
            if (!in_array($orderInfo['status'],[
                Status::USER_GOODS_ORDER_STATUS_WAITING_PAY,
                Status::USER_GOODS_ORDER_STATUS_WAITING_SEND,
            ])) {
                throw new Exception('该订单无法取消');
            }

            $mark = '后台管理员取消订单，原因：' . $reason;
            $this->shopOrAdminCancelOrder($orderInfo['order_number'],$mark);

            $trans->commit();
            return Functions::formatRestAPI(0, '取消成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

}
